#include "command.h"

//用于获取文件
void gets_file(int netFD, const char* name){

    //创建文件
    int fd = open(name, O_RDWR);
    if(fd == -1){
        off_t err = -1;
        send(netFD, &err, sizeof(err), MSG_NOSIGNAL);
    }else{
        struct stat file_st;
        fstat(fd, &file_st);
        int ret = send(netFD, &(file_st.st_size), sizeof(file_st.st_size), MSG_NOSIGNAL);
        ERROR_CHECK(ret, -1, "send_putsFile.c");
    }
    off_t flag;                                               
    recv(netFD, &flag, sizeof(off_t), MSG_WAITALL);
    if(flag == 1){
        fd = open(name, O_RDWR|O_CREAT, 0600);
        flag = 0;
    }else if(flag == 0){
        return ;
    }

    //留文件存储大小
    off_t file_size;
    int ret = recv(netFD, &file_size, sizeof(off_t), MSG_WAITALL);
    ERROR_CHECK(ret, -1, "recv_filesize_getsFile.c");
    ret = ftruncate(fd, file_size);
    //接收文件
    char *p = (char *)mmap(NULL, file_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, flag);
    ERROR_CHECK(p, NULL, "mmap_getsFile");
    ret = recv(netFD, p, file_size, MSG_WAITALL);
    ERROR_CHECK(ret, -1, "recv_file_getsFile.c");

    munmap(p, file_size);

    close(fd);
}
